﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 同步CRM物流发运单信息_晶硅
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoCRMWayBillInfoJGController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMStoCRMWayBillInfoJGController(ILogger<TMStoCRMWayBillInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMStoCRMWayBillInfoJGController>();
        }

        /// <summary>
        /// 同步CRM物流发运单信息_晶硅
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddCRMWayBillInfoJG([FromBody] TMStoCRMWayBillInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMWayBillInfoResponseDto re = new TMStoCRMWayBillInfoResponseDto();
            CRM_AddLogisticsInfoResponseDto strRe = new CRM_AddLogisticsInfoResponseDto();
            CRM_AddLogisticsInfoRequestDto strRequest = new CRM_AddLogisticsInfoRequestDto();
            string waybill_no = strparm.waybill_no;
            string ddm_token_crm = "%26token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY2NDg0NTIwNzk2MTciLCJ4ZGFwdXNlcmlkIjoiMTAwMzQwMTY3MDY0NjI5MDE4NjI0IiwieGRhcHRpbWVzdGFtcCI6IjA0MDhiZDhlY2VmZGM4NDg0MDkxOTBkOTM0NWUzMDBlOTFlZDQ3ZGQ1Y2ZhNTA0ODZhN2IzZWJmZjIzMTJhZjIzOWFlMjA5ZWJiZGI3OTNjZWYzZDE3ZWE1Y2RmYzJkMDAzNzhiYjUwYzM3NjdlMzE1NDI5YmIxNmNlMTgxYjUyYTZlYWM4MzE0Nzg3MDZlNTNkM2Q3NGY1OTlkZDVkNjdhYTdkNjY0MzQ1YjRhOWQwNTFmNzU3MTk3MjFlYWUwNjY3MGFlYzM1YzQ5NTczYTdmNDJhN2JiNTgwNTcifQ==&download=download&formId=67107c3d72a36d3165c8d3c5&uuid=0854437598cabccfe16c551e";
            int ydzt = 0;//运单状态
            int zt = 0;
            try
            {

                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }           
                if (strMsg == "")
                {
                    CRM_AddLogisticsInfo_header header_input = new CRM_AddLogisticsInfo_header();//operationinfo赋值
                    string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                    string systemid = "ecology9";
                    string password = "A5CB8E3D73834CC598DDC659C6F22523";
                    string Md5str = MethodHelp.GetMD5(systemid + password + currentDateTime);
                    header_input.systemid = systemid;
                    header_input.currentDateTime = currentDateTime;
                    header_input.Md5 = Md5str;
                    strRequest.header = header_input;//header节点赋值
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                    urldic.Add("function_description", "内部:新增物流信息");//查看URL配置表地址描述
                    DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                    if (url_dt.Rows.Count > 0)
                    {
                        dic.Add("waybill_no", waybill_no);
                        DataTable wl_dt = MethodHelp.GetTableInfo("TMS0082", dic, con);//晶硅物流信息获取
                        if (wl_dt.Rows.Count > 0)
                        {
                            foreach (DataRow item in wl_dt.Rows)
                            {



                                int sfyqs = 1;//是否签收
                                int shipping_status = 1;//运输状态
                                string qszt = "";
                                if (item["receipt_adjunct"].ToString() == "")
                                {
                                    sfyqs = 1;
                                    ydzt = 2;
                                    shipping_status = 1;
                                    qszt = "未签收";
                                }
                                else
                                {
                                    sfyqs = 0;
                                    ydzt = 4;
                                    shipping_status = 3;
                                    qszt = "已签收";
                                }

                             

                                List<CRM_AddLogisticsInfo_data> data_input = new List<CRM_AddLogisticsInfo_data>();//operationinfo赋值
                                CRM_AddLogisticsInfo_operationinfo operationinfo_input = new CRM_AddLogisticsInfo_operationinfo();//operationinfo赋值
                                CRM_AddLogisticsInfo_mainTable mainTable_input = new CRM_AddLogisticsInfo_mainTable();//mainTable赋值
                                List<CRM_AddLogisticsInfo_qsdfj> qsdfj_input = new List<CRM_AddLogisticsInfo_qsdfj>();

                                //operationinfo_input赋值
                                operationinfo_input.operationDate = DateTime.Now.ToString("yyyy-MM-dd");
                                operationinfo_input.operationTime = DateTime.Now.ToString("HH:mm:ss");
                                operationinfo_input.creator = wl_dt.Rows[0]["account"].ToString();

                                if (item["receipt_adjunct"].ToString() != "")
                                {
                                    var fj = JsonConvert.DeserializeObject<DDM_FJ_signin_adjunct[]>(item["receipt_adjunct"].ToString());
                                    if (fj != null)
                                    {
                                        foreach (var rows in fj)
                                        {
                                            //mainTable_input赋值
                                            qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                            {
                                                name = rows.fileName,
                                                content = rows.url + ddm_token_crm
                                            });
                                        }
                                    }
                                }
                                else
                                {   //mainTable_input赋值
                                    qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                    {
                                        name = "无",
                                        content = ""
                                    });

                                }
                                mainTable_input.qsdfj = qsdfj_input;
                                mainTable_input.xsddh = item["saleorder_no"].ToString();
                                mainTable_input.ddxh = item["saleorderline_no"].ToString();
                                mainTable_input.qssl = DB.ToDecimal(item["rec_qty"].ToString());
                                mainTable_input.wlfy = 0;
                                mainTable_input.yszt = DB.ToInt(shipping_status);
                                mainTable_input.sfyqs = sfyqs;
                                mainTable_input.qsrq = DB.ToDateTime(item["receipt_date"].ToString()).ToString("yyyy-MM-dd");
                                mainTable_input.khbm = item["waybill_no"].ToString();
                                mainTable_input.cph = item["car_no"].ToString();
                                mainTable_input.wlbm = item["material_code"].ToString();
                                mainTable_input.wlmc = item["material_name"].ToString();
                                mainTable_input.wldw = "";
                                mainTable_input.ddsl = DB.ToDecimal(item["saleorder_qty"].ToString());
                                mainTable_input.pdatjsl = DB.ToDecimal(item["qty"].ToString());
                                mainTable_input.fhdz = item["shipping_address"].ToString();
                                mainTable_input.shdz = item["delivery_address"].ToString();
                                mainTable_input.shr = item["customer_contacts"].ToString();
                                mainTable_input.shdh = item["contacts_tel"].ToString();
                                mainTable_input.xshth = item["customerpo"].ToString();
                                mainTable_input.qsdh = item["receipt_no"].ToString();
                                mainTable_input.qszt = qszt;
                                mainTable_input.sj = item["driver_name"].ToString();
                                mainTable_input.khmc = item["customer_name"].ToString();
                                mainTable_input.chrq = DB.ToDateTime(item["shipping_date"].ToString()).ToString("yyyy-MM-dd"); ;
                                mainTable_input.hth = item["customerpo"].ToString();
                                mainTable_input.ddlx = "";
                                mainTable_input.fhsl = DB.ToDecimal(item["qty"].ToString());
                                mainTable_input.ydzt = ydzt;
                                mainTable_input.khbh = item["customer_code"].ToString();
                                mainTable_input.xsddid = item["saleorder_no"].ToString();
                                mainTable_input.xsddxid = item["saleorderline_no"].ToString();
                                mainTable_input.ckdh = item["delivery_no"].ToString();
                                mainTable_input.songhdh = item["delivery_no"].ToString();
                                mainTable_input.yjft = 0;
                                mainTable_input.fyjhls = "";
                                mainTable_input.zt = zt;
                                mainTable_input.ydzbid = item["id"].ToString();
                                mainTable_input.xsddmxid = item["autoid"].ToString();
                                mainTable_input.szjd = item["factory_code"].ToString();


                                if (mainTable_input != null && operationinfo_input != null)
                                {
                                    data_input.Add(new CRM_AddLogisticsInfo_data
                                    {
                                        operationinfo = operationinfo_input,
                                        mainTable = mainTable_input
                                    });
                                }

                                if (data_input != null)
                                {
                                    strRequest.data = data_input;
                                }

                                string jsonText = JsonConvert.SerializeObject(strRequest);
                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                CRM_AddLogisticsInfoResponseDto psp = JsonConvert.DeserializeObject<CRM_AddLogisticsInfoResponseDto>(reAgv);
                                if (psp.status != "1")
                                {
                                    strMsg = strMsg + "-" + "CRM ERR:" + psp.datajson;
                                }

                            }
                        }
                        else
                        {
                            strMsg = "单号=<" + waybill_no + "> 找不到对应明细记录!";
                        }
                    }                 
                    
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
